package com.mycompany.j2eem.service.wrjservice;


import com.mycompany.j2eem.Entity.bean.*;
import com.mycompany.j2eem.Mapper.wrjmapper.RecommendationMapper;
import com.mycompany.j2eem.Mapper.wrjmapper.SearchMapper;
import com.mycompany.j2eem.recommend.ItemCF;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author wurj
 * @time 2019/4/16 13:56
 * @description
 */
@Service
public class RecommendationService {

    @Autowired
    RecommendationMapper recommendationMapper;
    @Autowired
    SearchMapper searchMapper;

    public List<PictureObjectBean> recommend_pic_service(String username, boolean isTag) {
        List<PictureObjectBean> pictureBeans = new ArrayList<>();
        String user = username;
        ItemCF itemDemo = new ItemCF(isTag, recommendationMapper);
        if (itemDemo.getRecommendItems().size() != 0) {
            itemDemo.setTargetUserIndex(itemDemo.getUesrIndex(user));
            if (itemDemo.getTargetUserIndex() == null) {
                System.out.println("没有该用户");
            } else {
                itemDemo.setTargetUserLikedPic(Arrays.asList(itemDemo.getAllUserPicLikesList()[itemDemo.getTargetUserIndex()]));

                itemDemo.calculateSim();

                itemDemo.getAllRecommendPics();

                System.out.println("推荐图片列表：");

                if (!isTag) {
                    for (Map.Entry<Integer, Object> item : itemDemo.getRecommendList()) {
                        System.out.println(itemDemo.getPictures().get(item.getKey()).getPictureId() + " " +
                                itemDemo.getPictures().get(item.getKey()).getPictureUrl());

                        pictureBeans.add(new PictureObjectBean(itemDemo.getPictures().get(item.getKey()).getPictureId(),
                                itemDemo.getPictures().get(item.getKey()).getPictureUrl()));
                    }
                }
            }

        }
        return pictureBeans;
    }


    public List<TagObjectBean> recommend_tag_service(String username, boolean isTag) {
        List<TagObjectBean> tagBeans = new ArrayList<>();
        String user = username;
        ItemCF itemDemo = new ItemCF(isTag, recommendationMapper);

        if (itemDemo.getRecommendItems().size() != 0) {
            itemDemo.setTargetUserIndex(itemDemo.getUesrIndex(user));
            if (itemDemo.getTargetUserIndex() == null) {
                System.out.println("没有该用户");
            } else {
                itemDemo.setTargetUserLikedPic(Arrays.asList(itemDemo.getAllUserPicLikesList()[itemDemo.getTargetUserIndex()]));

                itemDemo.calculateSim();

                itemDemo.getAllRecommendPics();

                System.out.println("推荐tag列表：");

                if (isTag) {
                    for (Map.Entry<Integer, Object> item : itemDemo.getRecommendList()) {
                        System.out.println(itemDemo.getTags().get(item.getKey()).getTagId() + " " +
                                itemDemo.getTags().get(item.getKey()).getTagname());


                        tagBeans.add(new TagObjectBean(itemDemo.getTags().get(item.getKey()).getTagId(), itemDemo.getTags().get(item.getKey()).getTagname()));
                    }
                }
            }
        }
        return tagBeans;
    }

    public List<String> getTagIdService() {

        List<TagMapperBean> tagMapperBeanList = searchMapper.getTags();
        List<String> tagsId = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            int a = (int) (Math.random() * (tagMapperBeanList.size() - 1));
            if (!tagsId.contains(Integer.toString(a))) {
                tagsId.add(Integer.toString(a));

            }
        }
        return tagsId;
    }

    public List<PictureInDBBean> getPic(List<String> hotTag) {
        List<PictureInDBBean> pictureObjectBeans = new ArrayList<>();
        for (String s : hotTag) {
            List<PictureInDBBean> pictureInDBS = searchMapper.getPictures(s);
            if (pictureInDBS.size() == 0)
                continue;
            else {
                for (int i = 0; i < 5; i++) {
                    Double b = Math.random();

                    Double a = b * pictureInDBS.size();
                    int c = a.intValue();

                    PictureInDBBean pictureInDBBean = pictureInDBS.get(c);
                    if (!pictureObjectBeans.contains(pictureInDBBean)) {

                        pictureObjectBeans.add(pictureInDBBean);
                    }
                }
            }
        }
        return pictureObjectBeans;
    }

    public List<String> getHotTagIdService() {
        List<String> tags = new ArrayList<>();
        List<String> ids = getTagIdService();
        for (String s : ids) {
            tags.add(recommendationMapper.getTagNameByTagNameId(s));
        }
        return tags;
    }

    public List<RcmdUser> recommend_users(String username) {
        List<RcmdUser> rcmdUsers = new ArrayList<>();
        List<UserBean> userBeans = new ArrayList<>();
        List<RcmdUser> push = new ArrayList<>();
        String accountID = searchMapper.getAccountID(username);

        if (accountID != null) {
            List<String> likePics = searchMapper.getAccountLikePics(accountID);
            List<RecommendItem> all = recommendationMapper.getAllMessage();
            List<RecommendItem> allFilter=new ArrayList<>();

            if (all.size() != 0) {
                for(int i=0;i<all.size();i++){

                    if (!all.get(i).getAccount_id().equals(accountID)) {
                        allFilter.add(all.get(i));
                    }
                }
                if (allFilter.size()==0){
                    push = random(accountID);
                    return push;
                }


                userBeans = constructUsers(allFilter);



                for (UserBean userBean : userBeans) {
                    if (userBean.getUserId().equals(accountID))
                        userBeans.remove(userBean);
                }

                rcmdUsers = calulateSim(likePics, userBeans);    //相似度包含

                compareSim(rcmdUsers);

                int count = 3;
                int i = 0;
                if (rcmdUsers.size()==0){
                    push = random(accountID);
                    return push;
                }

                while (count >= 0 || rcmdUsers.size() < 3) {

                    push.add(rcmdUsers.get(i++));
                    count--;
                }

                for (RcmdUser rcmdUser : push) {
                    String id = searchMapper.getUserIDByAccountId(rcmdUser.getId());
                    String userName = searchMapper.getUserName(id);
                    String headPath = searchMapper.getUserHeadPath(id);
                    rcmdUser.setId(id);
                    rcmdUser.setName(userName);
                    rcmdUser.setHeadPath(headPath);

                }
            } else {
                push = random(accountID);
            }
            return push;
        } else {
            push = random(accountID);
            return push;
        }
    }

    private List<RcmdUser> random(String accountId) {
        List<String> all = searchMapper.getAllAccountId();
        List<String> id = new ArrayList<>();
        List<RcmdUser> random = new ArrayList<>();
        String userId=searchMapper.getUserIDByAccountId(accountId);

        while (random.size()==0){
            for (int i = 0; i <= 1; i++) {
                Double a = Math.random() * (all.size()+1);
                Integer b = a.intValue();
                if (!id.contains(b.toString())&&b.toString()!=userId){
                    id.add(b.toString());
                }
            }
            for (String s : id) {
                String userID = searchMapper.getUserIDByAccountId(s);
                String userName = searchMapper.getUserName(userID);
                String headPath = searchMapper.getUserHeadPath(userID);
                if (userID != s && userID != null){
                    if (random.size()==0){

                        random.add(new RcmdUser(userID, userName, headPath));
                    }else {
                        for (int i=0;i<random.size();i++) {
                            if (random.get(i).getId() != userID){

                                random.add(new RcmdUser(userID, userName, headPath));
                            }
                        }
                    }

                }
            }
        }


        return random;
    }

    private void compareSim(List<RcmdUser> rcmdUsers) {
        RcmdUser rcmdUser = new RcmdUser();
        for (int i = 0; i < rcmdUsers.size(); i++) {
            for (int j = i; j < rcmdUsers.size(); j++) {
                if (rcmdUsers.get(i).getSim() <= rcmdUsers.get(j).getSim()) {
                    rcmdUser.setId(rcmdUsers.get(j).getId());
                    rcmdUser.setName(rcmdUsers.get(j).getName());

                    rcmdUsers.get(j).setId(rcmdUsers.get(i).getId());
                    rcmdUsers.get(j).setId(rcmdUsers.get(i).getName());

                    rcmdUsers.get(i).setId(rcmdUser.getId());
                    rcmdUsers.get(i).setId(rcmdUser.getName());
                }
            }
        }
    }

    private List<UserBean> constructUsers(List<RecommendItem> recommendItems) {
        List<UserBean> userBeans = new ArrayList<>();
        for (int i = 0; i < recommendItems.size(); i++) {

            String accountId = recommendItems.get(i).getAccount_id();
            String picId = recommendItems.get(i).getPicture_id();
            if (userBeans.size() != 0) {
                for (int j=0;j<userBeans.size();j++){

                    UserBean userBean = userBeans.get(j);
                    if (!userBean.getUserId().equals(accountId) || userBean.getUserId().equals(null)) {
                        userBeans.add(new UserBean(i, accountId, recommendationMapper.getUserName(accountId)));//在当前的index，用户id，名字
                        userBeans.get(j).addLikePic(picId);
                    } else {
                        System.out.println("执行第二个");
                        userBean.addLikePic(picId);
                    }
                }
            } else {
                System.out.println("第二个大If");
                UserBean userBean=new UserBean(i, accountId, recommendationMapper.getUserName(accountId));
                userBean.addLikePic(picId);
                userBeans.add(userBean);
            }
//            for (int j = 0; j <i; j++) {
//                System.out.println("循环");
//                if (userBeans.size() != 0) {
//                    System.out.println("i= "+i+" j= "+j+" userB = "+userBeans.size());
//                    UserBean userBean = userBeans.get(j);
//                    if (!userBean.getUserId().equals(accountId) || userBean.getUserId().equals(null)) {
//                        System.out.println("执行第一个");
//                        userBeans.add(new UserBean(i, accountId, recommendationMapper.getUserName(accountId)));//在当前的index，用户id，名字
//                        userBeans.get(j).addLikePic(picId);
//                    } else {
//                        System.out.println("执行第二个");
//                        userBean.addLikePic(picId);
//                    }
//                } else {
//                    System.out.println("第二个大If");
//                    userBeans.add(new UserBean(i, accountId, recommendationMapper.getUserName(accountId)));//在当前的index，用户id，名字
//                    userBeans.get(j).addLikePic(picId);
//                }
//            }
        }
        return userBeans;
    }

    private List<RcmdUser> calulateSim(List<String> like, List<UserBean> userBeans) {
        int count = 0;
        List<RcmdUser> rcmdUsers = new ArrayList<>();
        for (UserBean userBean : userBeans) {
            for (String s : like) {

                if (userBean.getLikeId().contains(s))
                    count++;
            }
            long self = count / like.size();
            long other = count / like.size();

            if (self==0){
                continue;
            }else
                rcmdUsers.add(new RcmdUser(userBean.getUserId(), (other / self) - 1));
        }
        return rcmdUsers;
    }

//    public static void main(String[] args) {
//        JiebaSegmenter jiebaSegmenter=new JiebaSegmenter();
//        String s="王家辉姚斯源高鸿赟吴淳阳武荣甲";
//        List<SegToken> list=jiebaSegmenter.process(s, JiebaSegmenter.SegMode.SEARCH);
//        for (SegToken segToken:list){
//            System.out.println(segToken);
//        }
//
//        for (int i=0;i<5;i++){
//            System.out.println(i+"次  "+(int)(Math.random()*(list.size()-1)));
//        }
//
//        Word2Vec word2Vec=new Word2Vec();
//        long start = System.currentTimeMillis();
//        try {
//            word2Vec.loadGoogleModel("./jar/word2vec.bin");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        float a= word2Vec.wordSimilarity("北京","南京");
//        //a=word2Vec.fastSentenceSimilarity(Arrays.asList("明月松间照"),Arrays.asList("清泉石上流"));
//        System.out.println("1 "+a+"   use time="+(System.currentTimeMillis()-start));
//
//        start=System.currentTimeMillis();
//        try {
//            word2Vec.loadJavaModel("./jar/trained_model");
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//        float b= word2Vec.wordSimilarity("北京","南京");
//        //a=word2Vec.fastSentenceSimilarity(Arrays.asList("明月松间照"),Arrays.asList("清泉石上流"));
//        System.out.println("2: "+b+"   use time="+(System.currentTimeMillis()-start));
//    }
}
